package org.example;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.log4j.Logger;
import org.example.Command.SendMessage;
import org.example.Handler.MainServerHandler;
import org.example.Handler.RecvCommandServerHandler;
import org.example.Handler.SendCommandServerHandler;
import org.example.Handler.ShowCommandServerHandler;
import org.example.protocol.MessageCodec;
import org.example.protocol.ProtocolFrameDecoder;

import static org.example.Poll.init;
import static org.example.Utils.StringUtils.getNext;

public class Server {
    public static Logger log = Logger.getLogger(Server.class);

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        //初始化
        init();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    ch.pipeline().addLast(new MessageCodec());
                    ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            if (event.state() == IdleState.READER_IDLE) {
                                ctx.channel().close();
                            }
                        }
                    });
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<SendMessage>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, SendMessage msg) throws Exception {
                            //由服务器分发sequenceId
                            msg.setSequenceId(getNext());
                            ctx.writeAndFlush(msg);
                        }

                    });
                    ch.pipeline().addLast("Recv handler", new RecvCommandServerHandler());
                    ch.pipeline().addLast("Show handler", new ShowCommandServerHandler());
                    ch.pipeline().addLast("Send handler", new SendCommandServerHandler());
                    ch.pipeline().addLast("server handler", new MainServerHandler());
                }
            });
            Channel channel = serverBootstrap.bind(8082).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
